/**
 * Copyright 2005-2015 ixiangshou.com
 * All rights reserved.
 * 
 * @project
 * @author Flouny.Caesar
 * @version 1.0
 * @data 2013-10-01
 */
package com.enjoy.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.core.util.FileUtil;
import com.core.util.GlobEnv;
import com.core.util.JSONUtils;
import com.core.util.StringUtil;
import com.core.zui.adapter.EasyGridDataAdapter;
import com.core.zui.dataobject.grid.EasyGridHTTPObject;
import com.core.zui.helper.GridHelper;
import com.core.zui.helper.HelperTools;
import com.core.zui.hub.DefaultAjaxWidgetHub;
import com.core.zui.hub.transfer.DateTimeTransfer;
import com.core.zui.widgets.Grid;
import com.enjoy.model.pojo.Pic;
import com.enjoy.model.vo.BizUserVO;
import com.enjoy.model.vo.PicVO;
import com.enjoy.model.vo.ShopVO;
import com.enjoy.service.BizUserService;
import com.enjoy.service.PicEntityService;
import com.enjoy.service.PicService;
import com.enjoy.service.ShopEntityService;
import com.enjoy.service.ShopService;

@Controller
public class ShopController {

	@Autowired
	private ShopService shopService;
	
	@Autowired
	private ShopEntityService shopEntityService;
	
	@Autowired
	private PicService picService;
	
	@Autowired
	private PicEntityService picEntityService;
	
	@Autowired
	private BizUserService bizUserService;
	
	/**
	 * 门店相册类型
	 */
	private static final String SHOP_PIC_TYPE = "2";
	
	private Logger LOG = LoggerFactory.getLogger(ShopController.class);
	
	/**
	 * 首页
	 * @return
	 */
	@RequestMapping("/shop/index")
	public String index(){
		
		return "/shop/index";
	}
	
	/**
	 * grid分页列表
	 * @param shopVO
	 * @param request
	 * @return
	 */
	@RequestMapping("/shop/grid")
	public @ResponseBody String grid(ShopVO shopVO,HttpServletRequest request){
		EasyGridHTTPObject httpObject = new EasyGridHTTPObject(request);
		Grid grid = new Grid(new EasyGridDataAdapter());
		grid.setHTTPObject(httpObject);
		
		DefaultAjaxWidgetHub hub = new DefaultAjaxWidgetHub();
		hub.addTransfer(Date.class, new DateTimeTransfer());
		GridHelper helper = (GridHelper) HelperTools.getHelper(GridHelper.class);
		helper.setHub(hub);
		
		if(StringUtil.isBlank(shopVO.getStatus())){
			shopVO.setStatus("1");
		}
		
		grid.setTotalCount(shopService.getShopCount(shopVO));
		List<ShopVO> shopList = shopService.getPageShops(shopVO, httpObject);
		grid = helper.createGrid(grid, shopList);
		
		return grid.toJSONString();
	}
	
	/**
	 * 门店详情
	 * @return
	 */
	@RequestMapping("/shop/detail")
	public String detail(ShopVO shopVO, Map<String,Object> mode){
		
		if(shopVO.getId() != null && shopVO.getId() > 0){
			
			mode.put("shopVO", shopService.getShopById(shopVO.getId()));
			
			BizUserVO buvo = bizUserService.getBizUserBySId(shopVO.getId());
			if (buvo != null) {
				mode.put("account", buvo.getAccount());
			}
		}
		
		return "/shop/detail";
	}
	
	/**
	 * 门店新增
	 * @param shopVO
	 * @return
	 */
	@RequestMapping("/shop/add")
	public @ResponseBody String create(ShopVO shopVO,HttpServletRequest request){
		shopVO.setCirclesId(shopVO.getCircle());
		
		if(shopVO.getId() != null && shopVO.getId() > 0){
			return shopEntityService.update(shopVO) ? "yes" : "no";
		}
		
		return shopEntityService.create(shopVO) ? "yes" : "no";
	}
	
	/**
	 * 禁用门店
	 * @param shopVO
	 * @return
	 */
	@RequestMapping("/shop/disableShop")
	public @ResponseBody String disableShop(ShopVO shopVO){
		
		return shopEntityService.disableShop(shopVO.getIds(),shopVO.getStatus()) ? "yes" : "no";
	}
	
	/**
	 * 删除门店
	 * @param shopVO
	 * @return
	 */
	@RequestMapping("/shop/dropShop")
	public @ResponseBody String dropShop(ShopVO shopVO){
		
		return shopEntityService.dropShop(shopVO.getIds()) ? "yes" : "no";
	}
	
	/**
	 * 查看门店详情
	 * @param shopVO
	 * @return
	 */
	@RequestMapping("/shop/view")
	public String showShop(ShopVO shopVO,Map<String,Object> map){
		if(shopVO.getId() != null && shopVO.getId() > 0){
			
			map.put("shopVO", shopService.getShopById(shopVO.getId()));
		}
		return "/shop/view";
	}
	
	/**
	 * 上传图片文件
	 * @param shopVO
	 * @param map
	 * @return
	 */
	@RequestMapping("/shop/uploadPic")
	public String uploadDialog(PicVO picVO,Map<String,Object> map){
		
		map.put("pic", picVO);
		
		return "/shop/upload";
	}
	
	/**
	 * 图像
	 * @param picVO
	 * @param map
	 * @return
	 */
	@RequestMapping("/shop/pho")
	public String photos(PicVO picVO,Map<String,Object> map){
		picVO.setType(SHOP_PIC_TYPE);
		map.put("picList", picService.queryForAll(picVO));
		
		return "/shop/pho";
	}
	
	
	/**
	 * 上传文件
	 * @param pic
	 * @param request
	 * @return
	 */
	@RequestMapping("/shop/pic")
	public @ResponseBody String uploadPic(HttpServletRequest request){
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile pic = multipartRequest.getFile("Filedata");
		String id = multipartRequest.getParameter("id");
		String date = DateUtil.formatDate(new Date(), "yyyyMMdd");

		String dir = GlobEnv.get("upload.pic").concat("/").concat(date);
		
		String filename = pic.getOriginalFilename();
		String extension = FilenameUtils.getExtension(filename);
		
		String newName = String.valueOf(new Date().getTime()).concat(".").concat(extension);
		String smailName = "s".concat(newName);
		
		try {
			
			File dirFile = new File(dir);
			if(!dirFile.exists()){
				dirFile.mkdirs();
			}
			
			String newFile = GlobEnv.get("upload.pic").concat("/").concat(date).concat("/").concat(newName);
			
			String smailFile = GlobEnv.get("upload.pic").concat("/").concat(date).concat("/").concat(smailName);
			
			FileUtil.copyInputStreamToFile(pic.getInputStream(), new File(newFile));
			Thumbnails.of(pic.getInputStream()).size(130, 130).toFile(new File(smailFile));
			
			ShopVO shopVO = new ShopVO();
			shopVO.setId(Integer.parseInt(id));
			shopVO.setPicPath(date.concat("/").concat(smailName));
			shopEntityService.update(shopVO);
		} catch (IOException e) {
			LOG.error(e.getMessage(),e);
		}
		
		return GlobEnv.get("browse.pic").concat("/").concat(date).concat("/").concat(smailName);
	}
	
	/**
	 * 上传门店相册图片
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping("/shop/upload_pho")
	public @ResponseBody String uploadPhoto(HttpServletRequest request,Map<String,String> map){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile pic = multipartRequest.getFile("Filedata");
		String name = multipartRequest.getParameter("name");
		String shopId = multipartRequest.getParameter("shopId");
		String date = DateUtil.formatDate(new Date(),"yyyyMMdd");
		
		String filename = pic.getOriginalFilename();
		String extension = FilenameUtils.getExtension(filename);
		
		String newName = String.valueOf(new Date().getTime()).concat(".").concat(extension);
		String newFile = GlobEnv.get("upload.pic").concat("/").concat(date).concat("/").concat(newName);
		
		String smailName = "s".concat(newName);
		String smailFile = GlobEnv.get("upload.pic").concat("/").concat(date).concat("/").concat(smailName);
		try {
			String dirFile = GlobEnv.get("upload.pic").concat("/").concat(date).concat("/");
			File file = new File(dirFile);
			if(!file.exists()){
				file.mkdirs();
			}
			
			
			FileUtil.copyInputStreamToFile(pic.getInputStream(), new File(newFile));
			Thumbnails.of(pic.getInputStream()).size(130, 130).toFile(new File(smailFile));
			
			Pic pho = new Pic();
			pho.setShopId(Integer.parseInt(shopId));
			pho.setPath(date.concat("/").concat(smailName));
			pho.setName(name);
			pho.setType(SHOP_PIC_TYPE);
			
			picEntityService.create(pho);
		} catch (IOException e) {
			LOG.error(e.getMessage(),e);
		}
		
		map.put("path", GlobEnv.get("browse.pic").concat("/").concat(date).concat("/").concat(smailName));
		map.put("name", name);
		
		return JSONUtils.toJSONString(map);
	}
	
	/**
	 * 删除门店相册
	 * @param picVO
	 * @return
	 */
	@RequestMapping
	public @ResponseBody String dropPhotos(PicVO picVO){
		
		List<PicVO> picList = picService.queryForAll(picVO);
		for(PicVO pic : picList){
			String smailPath = GlobEnv.get("upload.pic").concat("/").concat(pic.getPath());
			String path = pic.getPath();
			
			String date = path.substring(0,path.indexOf("/"));
			String realName = path.substring(date.length()+2);
			String realPath = GlobEnv.get("upload.pic").concat("/").concat(date).concat("/").concat(realName);
			
			File oriFile = new File(realPath);
			File smFile = new File(smailPath);
			FileUtils.deleteQuietly(oriFile);
			FileUtils.deleteQuietly(smFile);
		}
		
		return picEntityService.drop(picVO) ? "yes" : "no";
	}
}
